package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.EditPassword;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 用户服务
 */
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
    BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;

    //根据用户名查询用户信息,包括用户的角色和角色关联的权限
    public User findByUsername(String username) {
        User user = userDao.findByUsername(username);//根据用户名查询用户表
        if (user == null) {
            return null;
        }
        Integer userId = user.getId();
        //根据用户id查询关联的角色
        Set<Role> roles = roleDao.findByUserId(userId);
        if (roles != null && roles.size() > 0) {
            //遍历角色集合，查询每个角色关联的权限
            for (Role role : roles) {
                Integer roleId = role.getId();//角色id
                //根据角色id查询关联的权限
                Set<Permission> permissions = permissionDao.findByRoleId(roleId);
                if (permissions != null && permissions.size() > 0) {
                    //角色关联权限集合
                    role.setPermissions(permissions);
                }
            }
            //用户关联角色集合
            user.setRoles(roles);
        }

        return user;
    }


    @Override//增
    public void add(User user ,Integer[] roleIds) {
        userDao.add(user);
        Integer userId = user.getId();
        this.setUserAndRole(userId,roleIds);
    }


    @Override//删
    public void deleteById(Integer id) {
        //查询是否被关联
        long count = userDao.selectCountByUserId(id);
        if (count > 0) {
            userDao.deleteConstraints(id);
            userDao.deleteById(id);
        }
        userDao.deleteById(id);
    }

    @Override//改
    public void edit(User user,Integer[] roleIds) {
        userDao.edit(user);
        userDao.deleteAssociation(user.getId());
        this.setUserAndRole(user.getId(),roleIds);
    }

    private void setUserAndRole(Integer userId, Integer[] roleIds) {
        if(roleIds !=null && roleIds.length > 0){
            for (Integer roleId : roleIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("userId",userId);
                map.put("roleId",roleId);
                userDao.setUserAndRole(map);
            }
        }
    }

    @Override//查
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<User> page = userDao.findByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override//通过id查用户管理
    public User findById(Integer id) {
        return userDao.findById(id);
    }



    @Override//批量导入
    public void addData(List<User> list) {
        if (list != null && list.size() > 0) {
            for (User user : list) {
                //判断用户是否存在
              long count= userDao.findCountByUsername(user.getUsername());
              if (count>0){
                    userDao.edit(user);
              }else{
                  userDao.addData(user);
              }
            }
    /*@Override
    public List<Role> findRoleNameByUserId(Integer userId) {
         return userDao.findRolesByUserId(userId);
    }*/
        }
    }

    @Override//查询所有用户
    public List<Role> findAll(){
        return userDao.findAll();
    }

    @Override
    public List<Integer> findRoleIdsNameByUserId(Integer userId) {
        return userDao.findUserIdsByRoleId(userId);
    }

    @Override
    public User findAllByUsername(String username) {
        return userDao.findAllByUsername(username);
    }

    @Override
    public void editUser(User user) {
        userDao.editUser(user);

    }

    @Override
    public boolean confirm(EditPassword password) {
        User byUsername = userDao.findByUsername(password.getUsername());
        String dbPass = byUsername.getPassword();
        return passwordEncoder.matches(password.getOldPass(),dbPass);
    }

    @Override
    public void editPassword(EditPassword password) {
        User user = new User();
        user.setUsername(password.getUsername());
        user.setPassword(passwordEncoder.encode(password.getPass()));
        userDao.editUser(user);
    }


}



